<script setup>
import { Message } from 'element-ui';
import { useRouter } from '@/router/index.js';
import { useRequest, useWatch } from '@/hooks';
import { useGlobalState } from '@/store/globalState.js';
import { useCascaderLink, engTypeDisplay } from '@/views/hooks.js';
import { useMain } from '@/store/app.js';
import { getList, getJCData, getProjectStage, getTGData, getDownloadPath } from '@/api/index.js';
import ToolTip from '@/components/ToolTip/index.vue';
import PortalListTable from './components/PortalListTable.vue';

const { projectType } = useMain();
const fileUrl = useGlobalState().globalState.fileUrl;
const showTable = ref(false);
const queryForm = ref(null);
const amountRes = ref(null);
const carousel = ref(null);
const statusList = ref([]);
const [, , statusRun] = useRequest(getProjectStage, {
  defaultParams: [projectType],
  onSuccess: res => {
    statusList.value = res?.data?.filter(n => {
      return n.value !== '无';
    });
    statusList.value.unshift({ key: null, value: '全部' });
  },
});
const cascaderRun = () => {
  runEnt({ projectType: queryParams.value.type });
  queryParams.value.province = '山西省';
  queryParams.value.city = cascader.value?.[1] ?? null;
  queryParams.value.county = cascader.value?.[2] ?? null;
};
const [cascader, cascaderProps, areaList, cascaderChange] = useCascaderLink(cascaderRun);
const queryParams = ref({
  type: projectType,
  inName: null,
  province: '山西省',
  city: null,
  county: null,
  projectStatus: projectType === 'TG' ? 'OPERATION' : 'JCOPERATION',
});
const [entSelectList, , runEnt] = useRequest(getList, {
  defaultParams: [{ projectType: projectType }],
  // manual: true,
});
const JCLists = ref({});
const [, JCLoading, runJCList] = useRequest(getJCData, {
  manual: true,
  defaultParams: [queryParams.value],
  onSuccess: res => {
    if (res.code === 200) {
      let obj = {
        ...res.data,
      };
      obj.institutionListJcList.forEach(async n => {
        const data = await getDownloadPath(n?.imgUrl);
        n.imgUrl = fileUrl + data.data.url;
      });
      JCLists.value = obj;
    } else {
      JCLists.value = {};
    }
  },
  onError: () => {
    TGLists.value = {};
  },
});
const TGLists = ref({});
const [, TGLoading, runTGList] = useRequest(getTGData, {
  defaultParams: [queryParams.value],
  manual: true,
  onSuccess: res => {
    if (res.code === 200) {
      let obj = {
        ...res.data,
      };
      obj.institutionListTgList.forEach(async n => {
        const data = await getDownloadPath(n?.imgUrl);
        n.imgUrl = fileUrl + data.data.url;
      });
      TGLists.value = obj;
    } else {
      TGLists.value = {};
    }
  },
  onError: () => {
    TGLists.value = {};
  },
});
projectType === 'TG' ? runTGList(queryParams.value) : runJCList(queryParams.value);
// const params = ref({ belong: '0', enterpriseCode: null });
// const [amountRes, , runAmount] = useRequest(, {
//   defaultParams: [params.value],
//   staleTime: 60 * 60 * 1000, // 5 minutes
//   cacheKey: params => params?.[0].enterpriseCode,
//   manual: true,
// });
const handleQuery = () => {
  queryParams.value.type === 'TG' ? runTGList(queryParams.value) : runJCList(queryParams.value);
};
const resetQuery = () => {
  cascader.value = ['山西省'];
  queryParams.value.province = '山西省';
  queryParams.value.city = null;
  queryParams.value.county = null;
  queryParams.value.inName = null;
  queryParams.value.projectStatus = queryParams.value.type === 'TG' ? 'OPERATION' : 'JCOPERATION';
  queryParams.value.type === 'TG' ? runTGList(queryParams.value) : runJCList(queryParams.value);
};
const curEntShow = ref(null);
const handleHover = (e, item, index) => {
  curEntShow.value = e.type === 'mouseenter' ? item?.enterpriseCode : null;
  amountRes.value = item;
  if (e.type === 'mouseenter') {
    carousel.value[index].setActiveItem('1');
    // runAmount({ ...params.value, enterpriseCode: item.enterpriseCode });
  }
};
const router = useRouter();
const isQiankun = window.__POWERED_BY_QIANKUN__;
const handleClick = item => {
  sessionStorage.setItem('amountRes', JSON.stringify(amountRes.value));
  sessionStorage.setItem('entInfo', JSON.stringify(item));
  const TGQuery = { TGCode: item.enterpriseCode };
  const JCQuery = { JCCode: item.enterpriseCode };
  if (item.statusName === '准备中' || item.statusName === '建设中') {
    Message.warning('该机构，准备中/建设中，无能耗数据');
  } else {
    if (isQiankun) {
      router.push({
        path: '/zhny/em/orgMgmt/overview',
        query: queryParams.value.type === 'TG' ? TGQuery : JCQuery,
      });
    }
  }
};
useWatch(
  () => queryParams.value.type,
  n => {
    queryParams.value.inName = null;
    queryParams.value.queryParams = n;
    cascader.value = '山西省';
    statusRun(n);
    runEnt({ projectType: n });
    if (n === 'TG') {
      queryParams.value.projectStatus = 'OPERATION';
      runTGList(queryParams.value);
    } else {
      queryParams.value.projectStatus = 'JCOPERATION';
      runJCList(queryParams.value);
    }
  },
);
</script>
<template>
  <div class="app-container">
    <div class="searBox u-mb20 u-df-spb">
      <el-form :model="queryParams" ref="queryForm" :inline="true">
        <el-form-item prop="type">
          <el-radio-group v-model="queryParams.type" size="small">
            <el-radio-button label="JC">监测</el-radio-button>
            <el-radio-button label="TG">托管</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="行政区划">
          <el-cascader
            v-model="cascader"
            :props="cascaderProps"
            :options="areaList"
            placeholder="请选择行政区划"
            size="small"
            style="width: 240px"
            clearable
            @visible-change="cascaderChange"
          ></el-cascader>
        </el-form-item>
        <el-form-item prop="inName" label="机构名称">
          <el-select
            v-model="queryParams.inName"
            value-key="enterpriseName"
            placeholder="请输入机构名称"
            filterable
            size="small"
            style="width: 240px"
          >
            <el-option
              v-for="(val, index) in entSelectList"
              :key="`${val.enterpriseCode}-${index}`"
              :label="val.enterpriseName"
              :value="val.enterpriseName"
            />
          </el-select>
        </el-form-item>
        <el-form-item prop="projectStatus" :label="queryParams.type === 'JC' ? '机构监测状态' : '机构托管状态'">
          <el-select
            v-model="queryParams.projectStatus"
            :placeholder="queryParams.type === 'JC' ? '机构监测状态' : '机构托管状态'"
            size="small"
            style="width: 240px"
          >
            <el-option v-for="(val, index) in statusList" :key="index" :label="val.value" :value="val.key" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="small" @click="handleQuery">搜索</el-button>
          <el-button size="small" type="primary" plain @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
      <i class="el-icon-s-grid u-primary u-mb20 cursor" style="font-size: 24px" @click="showTable = !showTable"></i>
    </div>
    <el-row v-show="!showTable" v-loading="TGLoading || JCLoading" :gutter="20" class="portalList-wrapper">
      <el-col
        v-for="(item, index) in queryParams.type === 'TG'
          ? TGLists?.institutionListTgList ?? []
          : JCLists?.institutionListJcList ?? []"
        :key="item?.enterpriseCode"
        :span="6"
        class="u-mb20"
      >
        <div
          class="ent-item"
          :style="{
            background: item?.imgUrl ? `url(${item?.imgUrl}) center/100% no-repeat` : '',
          }"
          @mouseenter="handleHover($event, item, index)"
          @mouseleave="handleHover($event, item, index)"
        >
          <div class="ent-name u-df-ct" @click="handleClick(item)">
            <ToolTip :content="item?.inName" effect="dark" name="u-c-3f" />
          </div>
          <div class="curEntShow" v-show="curEntShow === item.enterpriseCode">
            <template v-if="queryParams.type === 'TG'">
              <el-carousel
                ref="carousel"
                trigger="click"
                :autoplay="true"
                :interval="3000"
                :loop="true"
                indicator-position="none"
              >
                <el-carousel-item name="1">
                  <ul class="u-df-ct u-box">
                    <li class="common-arcBg common-arcBg0">
                      <div>能耗用量</div>
                      <div>{{ amountRes?.usage ?? '--' }}</div>
                    </li>
                    <li class="common-arcBg common-arcBgY">
                      <div>节能总量</div>
                      <div>{{ amountRes?.saving ?? '--' }}</div>
                    </li>
                  </ul>
                  <ul class="u-df-ct u-box">
                    <li class="common-arcBg common-arcBgX">
                      <div style="font-size: 12px">减排量</div>
                      <div>{{ amountRes?.reduction ?? '--' }}</div>
                    </li>
                    <li class="common-arcBg common-arcBgXY">
                      <div>项目收益</div>
                      <div>{{ amountRes?.savingIncome ?? '--' }}</div>
                    </li>
                  </ul>
                </el-carousel-item>
                <el-carousel-item name="1">
                  <ul class="u-df-ct u-box">
                    <li class="common-arcBg common-arcBg0">
                      <div>托管合同总额</div>
                      <div>{{ amountRes?.agreementAmount ?? '--' }}</div>
                    </li>
                    <li class="common-arcBg common-arcBgY">
                      <div>托管阶段</div>
                      <div>{{ amountRes?.statusName ?? '--' }}</div>
                    </li>
                  </ul>
                  <ul class="u-df-ct u-box">
                    <li class="common-arcBg common-arcBgX">
                      <div>托管能源类型</div>
                      <div class="nowrap">{{ amountRes?.energyType ?? '--' }}</div>
                    </li>
                    <li class="common-arcBg common-arcBgXY">
                      <div style="font-size: 12px">投运时长</div>
                      <div>{{ amountRes?.runningTime ?? '--' }}</div>
                    </li>
                  </ul>
                </el-carousel-item>
              </el-carousel>
            </template>
            <template v-else>
              <ul class="u-df-ct u-box">
                <li class="common-arcBg common-arcBg0">
                  <div>监测能源类型</div>
                  <!-- <div>{{ engTypeDisplay(amountRes?.energyType) ?? '--' }}</div> -->
                  <div class="nowrap">{{ amountRes?.energyType ?? '--' }}</div>
                </li>
                <li class="common-arcBg common-arcBgY">
                  <div>投运时间</div>
                  <div>{{ amountRes?.runningTime ?? '--' }}</div>
                </li>
              </ul>
              <ul class="u-df-ct u-box">
                <li class="common-arcBg common-arcBgX">
                  <div>能耗总量(tce)</div>
                  <div>{{ amountRes?.usage ?? '--' }}</div>
                </li>
                <li class="common-arcBg common-arcBgXY">
                  <div>碳排放(tCO2e)</div>
                  <div>{{ amountRes?.carbonEmission ?? '--' }}</div>
                </li>
              </ul>
            </template>
            <img class="curEntShow-img" src="@/assets/images/ct.svg" alt="" />
          </div>
        </div>
      </el-col>
    </el-row>
    <PortalListTable
      v-show="showTable"
      v-loading="TGLoading || JCLoading"
      :tableData="
        queryParams.type === 'TG' ? TGLists?.institutionListTgList ?? [] : JCLists?.institutionListJcList ?? []
      "
      :type="queryParams.type"
      :showTable="showTable"
      class="portalList-wrapper"
    />
  </div>
</template>
<style lang="scss" scoped>
.portalList-wrapper {
  height: calc(100% - 100px);
  overflow-y: auto;
  overflow-y: overlay;
  scrollbar-width: none;
  ::-webkit-scrollbar {
    width: 0px;
    display: none; /* Chrome Safari */
  }
}
.ent-item {
  height: 230px;
  position: relative;
  .curEntShow {
    padding-top: 10px;
    position: absolute;
    top: 0;
    left: 0;
    height: calc(100% - 43px);
    width: 100%;
    background: #1d285d;
    opacity: 0.79;
    .curEntShow-img {
      position: absolute;
      width: 15%;
      left: 50%;
      top: 35.5%;
      transform: translateX(-50%);
    }
  }
}
.ent-name {
  box-sizing: border-box;
  width: 100%;
  height: 43px;
  padding: 0 20px;
  background-color: #1d285d;
  opacity: 0.79;
  position: absolute;
  bottom: 0;
  left: 0;
  cursor: pointer;
  z-index: 1000;
}
.u-box {
  width: 100%;
  height: 88px;
}
.common-arcBg {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: flex-start;
  width: calc(50% - 40px);
  height: 82%;
  margin: 6px;
  > div:first-child {
    color: #f5f5f5;
    font-size: 13px;
    margin-bottom: 5px;
  }
  > div:nth-child(2) {
    color: #00ebff;
    font-size: 16px;
    font-weight: bold;
  }
}
.common-arcBg0 {
  position: relative;
  padding-left: 30px;
  :before {
    content: '';
    position: absolute;
    width: 100%;
    height: 100%;
    top: 0;
    left: 0;
    z-index: -1;
    background: url('../../assets/images/arc_bg.svg') center/100% 100% no-repeat;
  }
}
.common-arcBgY {
  position: relative;
  align-items: flex-end;
  padding-right: 30px;
  ::before {
    content: '';
    position: absolute;
    width: 100%;
    height: 100%;
    top: 0;
    left: 0;
    z-index: -1;
    background: url('../../assets/images/arc_bg.svg') center/100% 100% no-repeat;
    transform: rotateY(180deg);
  }
}
.common-arcBgX {
  position: relative;
  padding-left: 30px;
  ::before {
    content: '';
    position: absolute;
    width: 100%;
    height: 100%;
    top: 0;
    left: 0;
    background: url('../../assets/images/arc_bg.svg') center/100% 100% no-repeat;
    z-index: -1;
    transform: rotateX(180deg);
  }
}
.common-arcBgXY {
  position: relative;
  align-items: flex-end;
  padding-right: 30px;
  ::before {
    content: '';
    position: absolute;
    width: 100%;
    height: 100%;
    top: 0;
    left: 0;
    background: url('../../assets/images/arc_bg.svg') center/100% 100% no-repeat;
    z-index: -1;
    transform: rotateX(180deg) rotateY(180deg);
  }
}
::v-deep .el-form-item {
  margin-bottom: 20px;
  height: 40px;
}
::v-deep .el-carousel__arrow {
  top: 30% !important;
}
.nowrap {
  width: calc(100% - 50px);
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
</style>
